let logining = false;

export const isLogining = () => logining;

export const resolverList: ((result: boolean) => void)[] = [];

export const login = async () => {
  const userStore = $store.user();
  userStore.clearUserInfo();
  userStore.userInfo = undefined;
  if (!logining) {
    let result = true;
    logining = true;
    const codeResult = await uni.login();
    if (codeResult.code) {
      let response: Result<ResponseData<LoginCustomerVO>>;
      // #ifdef MP-ALIPAY
      response = await $api.postAlipayAuth(
        {
          code: codeResult.code,
          scope: 'AUTH_BASE'
        },
        { auth: false }
      );
      // #endif
      // #ifdef MP-WEIXIN
      response = await $api.postWechatAuth(
        {
          code: codeResult.code,
          scope: 'AUTH_BASE'
        },
        { auth: false }
      );
      // #endif
      switch (response.__error) {
        case undefined:
          userStore.setUserInfo(response.data);
          while (resolverList.length) {
            resolverList.shift()?.(true);
          }
          break;
        default:
          while (resolverList.length) {
            resolverList.shift()?.(false);
          }
          result = false;
      }
    } else {
      uni.showModal({
        title: '登陆失败',
        content: '小程序获取获取 code 失败',
        showCancel: false
      });
      result = false;
    }
    logining = false;
    return result;
  } else {
    const result = await new Promise((resolve) => {
      resolverList.push(resolve);
    });
    return result;
  }
};
